package ai.yale.config;

import ai.yale.bean.User;
import ai.yale.dao.UserRepository;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;

/**
 * Created by asus on 2017/8/17.
 */
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Autowired
    UserRepository userRepository;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            String userId = serverHttpRequest.getServletRequest().getParameter("userId");
            System.out.println(userRepository);

            if (userId != null) {
                // 校验id
                List<User> user = userRepository.findById(userId);
                if (user.size() == 0) {
                    System.out.println("用户不存在");
                    return false;
                }
                map.put("userId", userId);
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
